package testtransaction;

import com.tedu.dao.UserMapper;
import com.tedu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description TODO
 * @Author dangxianyue
 * @Date 2024/5/7 14:23
 */
@Service
public class BizService {

    @Autowired
    private UserMapper userMapper;

    // 自己注入自己，此处也是代理对象：BizService$$EnhancerBySpringCGLIB$$dea8749d@6676
    @Autowired
    private BizService bizService;

    public void f() {
        // insertDb(); // this指向，事务会失效
        bizService.insertDb(); // 类内调用通过代理对象指向，事务生效
    }


    @Transactional(rollbackFor = Exception.class)
    public void insertDb() {
        final User user = new User();
        user.setUsername("林惊羽");
        user.setPassword("123456");
        userMapper.addUser(user);
        System.out.println("添加用户成功，新用户id：" + user.getId());
        throw new RuntimeException("测试抛出异常");
    }
}
